package org.study.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileUtils {
    public static String writeInstallSh(List<String> comments, String paths, String fileName) {
        return write(comments,paths,fileName+"_install.sh");
    }
    /**
     * 将shell命令先写入到文件，上传到linux服务器上。在执行shell脚本。
     *
     * @param comments 命令集合
     * @param paths    写在本地的地址
     * @param fileName 文件名称
     */
    public static String write(List<String> comments, String paths, String fileName) {
        String filePath = paths+ File.separator +fileName;
        try {
            createDirectory(paths);
            FileWriter fw = new FileWriter(filePath);
            fw.write("echo \"开始运行！\"\n");
            for (String comment : comments) {
                fw.write(comment);
                fw.write("\n");
            }
            fw.write("echo \"运行结束！\"");
            fw.flush();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 创建本地目录
     *
     * @param directory 目录
     */
    public static void createDirectory(String directory) throws IOException {
        Path path = Paths.get(directory);
        if (!Files.exists(path)) {
            Files.createDirectory(path);
        }
    }
}
